// pages/personalProfile/personalProfile.js
// pages/carDetail/carDetail.js
var app = getApp();
var main = require('../../utils/main.js');
var model = require('../../utils/model/model.js');
var util = require('../../utils/util.js');  
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    isDetail: true,
    imageUrl: app.globalData.imageUrl,
    reply: '',
    isAdd: true,
    inputFocus: false,
    page: 1,
    replyObj: {},
    userInfo: '',
    replyList: [],
    userDetail: {},
    loadMoreTxt: '正在加载数据。。。',
    loadMore: false,
    hasData: true,
    isSelf: false,
    reward: { money: '', content:''},
    canSubmit:false,
    viewbar: [{ txt: '资料', checked: true }, { txt: '留言', checked: false }, { txt: '打赏', checked: false }],
    loadSuccess:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(wx.getStorageSync('userInfo') != ''){
      that.setData({
        userInfo: JSON.parse(wx.getStorageSync('userInfo'))  
      })
    }
    if(options.id){
      if (that.data.userInfo.id == options.id) {
        that.setData({
          isSelf: true
        })
      }
      // that.getLeaveMes();
      this.getUserInfo(options.id);
      wx.showLoading();
    }else{
      wx.getStorage({
        key: 'userDetail',
        success: function (res) {
          wx.hideLoading();
          that.setData({
            loadSuccess: true
          })
          that.setData({
            userDetail: res.data,
            replyList: []
          })
          if (that.data.userInfo.id == that.data.userDetail.id) {
            that.setData({
              isSelf: true
            })
          }
          that.getLeaveMes();
        }
      })
    } 
    main.changeInput.apply(this, []);
  },
  getUserInfo:function(userId){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyUserInfo/getUserInfoDetailsById',
      data: {
        id: userId,
        userId:this.data.userInfo.id
      },
      success: function (res) {
        if (res.statusCode == 200) {
          wx.hideLoading();
          _this.setData({
            loadSuccess: true
          })
          if(res.data.success){
            res.data.data.birthday = util.formatDate(res.data.data.birthday);
            _this.setData({
              userDetail: res.data.data
            })
            _this.getLeaveMes();
          }
        }
      }
    })
  },
  getLeaveMes(flag) {//获取留言数据
    
    var _this = this;
    var param = { type: 1, otherSideId: this.data.userDetail.id };
    if (this.data.userInfo.id != this.data.userDetail.id){
      param.userId = this.data.userInfo.id;
      param.otherSideId = this.data.userDetail.id;
    }
    wx.request({
      url: app.globalData.httpApiCar + 'messageInfo/all', //仅为示例，并非真实的接口地址
      data: param,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var obj = {};
        res.data.data.forEach(function (ele) {
          ele.time = '';
          if (ele.createTime) {
            // ele.time = util.getHours(new Date(ele.create_date.replace(/-/g, "/")).getTime());
            ele.time = util.getHours(ele.createTime);
          }
          if (ele.messageInfos.length > 0) {
            ele.messageInfos.forEach(function (item) {
              if (item.createTime) {
                item.time = util.getHours(item.createTime);
              }
            })
          }
        })
        _this.setData({
          replyList: res.data.data
        })
      }
    })
  },
  addLeaveMes() {//留言发送按钮点击事件
    if (this.data.reply != '') {
      var formData = {
        userId: this.data.userInfo.id,
        otherSideId: this.data.userDetail.id,
        message: this.data.reply,
        status: 1,
        backupA: this.data.userDetail.id
      };
      if (this.data.isAdd) {
        formData.type = 1;
      } else {
        formData.type = 2;
        formData.otherSideId = this.data.replyObj.userId;
        if (this.data.replyObj.parentId) {
          formData.parentId = this.data.replyObj.parentId;
        } else {
          formData.parentId = this.data.replyObj.id;
        }
      }
      var that = this;
      wx.request({
        url: app.globalData.httpApiCar + 'messageInfo/save', //仅为示例，并非真实的接口地址
        data: formData,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              page: 1,
              reply: ''
            })
            that.getLeaveMes(true);
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  followTap: function (e) {//关注
    var that = this;
    if (that.data.userDetail.attentionCount == 0) {
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/save', //仅为示例，并非真实的接口地址
        data: {
          userId: this.data.userInfo.id,
          sourceId: that.data.userDetail.id,
          block: 1
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              'userDetail.attentionCount': 1
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/deleteAttentionRecordByParams', //仅为示例，并非真实的接口地址
        data: {
          userId: this.data.userInfo.id,
          sourceId: that.data.userDetail.id,
          block: 1
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              'userDetail.attentionCount': 0
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  thumbsTap: function (e) {//点赞
    var that = this;
    if (that.data.userDetail.likeCount == 0) {
      wx.request({
        url: app.globalData.httpApiCar + 'tGyLike/save', //仅为示例，并非真实的接口地址
        data: {
          userId: this.data.userInfo.id,
          sourceId: that.data.userDetail.id,
          block: 2
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              'userDetail.likeCount': 1
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.httpApiCar + 'tGyLike/deleteLikeRecordByParams', //仅为示例，并非真实的接口地址
        data: {
          userId: this.data.userInfo.id,
          sourceId: that.data.userDetail.id,
          block: 2
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              'userDetail.likeCount': 0
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  rewardTap:function(e){//打赏
    if (this.data.canSubmit){
      this.setData({
        canSubmit:false
      })
      var that = this;
      wx.request({
        url: app.globalData.httpApiCar + 'tGyReward/save', //仅为示例，并非真实的接口地址
        data: {
          fromUserId: this.data.userInfo.id,
          toUserId: that.data.userDetail.id,
          content: this.data.reward.content,
          money: this.data.reward.money
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.payMoney(res.data.data);
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  payMoney: function (item) {
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyReward/payRewardFee', //仅为示例，并非真实的接口地址
      data: {
        openId: app.globalData.openId,
        userId: this.data.userInfo.id,
        money: this.data.reward.money,
        orderId: item.id,
        backupA: item.transactionOrderNumber
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          that.requestPayment(res.data.data);
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  requestPayment: function (obj) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        wx.showModal({
          title: '提示',
          content: '打赏成功',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              that.setData({
                'reward.content': '',
                'reward.money': '',
                canSubmit: false
              })
            }
          }
        })
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              that.setData({
                canSubmit: true
              })
            }
          }
        })
      }
    })
  },
  complaint: function (e) {//投诉
    var that = this;
    wx.navigateTo({
      url: '/pages/complaint/complaint?userId='+this.data.userDetail.id,
    })
  },
  rewardInput:function(e){
    if (e.currentTarget.dataset.name =='money'){
      if (e.detail.value.indexOf('.') >= 0) {
        var arr = e.detail.value.split('.');
        if (arr.length > 2) {
          arr = [arr[0], arr[1]];
        }
        if (arr[1].length > 2) {
          this.setData({
            'reward.money': arr[0] + '.' + arr[1].substring(0, 2)
          })
        } else {
          this.setData({
            'reward.money': arr[0] + '.' + arr[1]
          })
        }
      }else{
        this.setData({
          'reward.money': e.detail.value
        })
      }
    }else{
      this.setData({
        'reward.content': e.detail.value
      })
    }
    if (this.data.reward.content && this.data.reward.money){
      this.setData({
        canSubmit:true
      })
    }else{
      this.setData({
        canSubmit: false
      })
    }
  },
  inputBlur: function (e) {
    this.setData({
      isAdd: true,
      reply: ''
    })
  },
  // 回复按钮点击事件
  reply: function (e) {
    this.data.replyObj = e.currentTarget.dataset.item;
    this.data.replyObj.index = e.currentTarget.dataset.index;
    this.setData({
      isAdd: false,
      inputFocus: true,
      replyObj: this.data.replyObj,
      reply: ''
    })
  },
  // tab也切换
  tanSwitch: function (e) {
    this.data.viewbar.forEach(function (ele){
      ele.checked=false;
    })
    this.data.viewbar[e.currentTarget.dataset.index].checked=true;
    this.setData({
      viewbar: this.data.viewbar
    })
    if (e.currentTarget.dataset.index==1){
      this.inputBlur();
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // wx.showNavigationBarLoading(); //在标题栏中显示加载
    // this.setData({
    //   page: 1
    // })
    // this.getLeaveMes(true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // var that = this;
    // if (that.data.hasData) {
    //   this.setData({
    //     loadMoreTxt: '正在加载数据。。。',
    //     loadMore: true,
    //     page: this.data.page + 1
    //   });
    //   this.getLeaveMes();
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})